package com.dhy.springboot01thymeleaf.controller;

import com.dhy.springboot01thymeleaf.dao.DepartmentDao;
import com.dhy.springboot01thymeleaf.dao.EmployeeDao;
import com.dhy.springboot01thymeleaf.pojo.Department;
import com.dhy.springboot01thymeleaf.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

@Controller
public class EmployeeController {

    @Autowired
    EmployeeDao employeeDao;
    @Autowired
    DepartmentDao departmentDao;

    //查询所有员工 返回列表页面
    @GetMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeDao.getAll();

        model.addAttribute("emps",employees);

        return "emp/list";
    }

    //来到员工添加页面
    @GetMapping("/emp")
    public String toAddPage(Model model){
        //查出所有部门在页面显示
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts",departments);
        return "emp/add";
    }

    //添加员工
    //SpringMVC自动将请求参数和入参对象的属性进行一一绑定(名字要一样)
    @PostMapping("/emp")
    public String addEmp(Employee employee){
        System.out.println("添加的员工数据："+employee);

        employeeDao.addEmployee(employee);

        //redirect：表示重定向
        //forward：表示转发
        return "redirect:/emps";
    }

    //来到修改页面，查出当前员工，在页面显示
    @GetMapping("/emp/{id}")
    public String toEditPage(@PathVariable("id") Integer id, Model model){
        Employee employee = employeeDao.getEmployeeById(id);
        model.addAttribute("emp",employee);

        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts",departments);

        //回到修改页面（add是一个修改添加二合一的页面）
        return "emp/add";
    }


    //员工修改 需要提交员工id
    @PutMapping("/emp")
    public String updateEmp(Employee employee){
        System.out.println("修改的员工数据："+employee);

        employeeDao.addEmployee(employee);

        return "redirect:/emps";
    }


    @DeleteMapping("/emp/{id}")
    public String deleteEmp(@PathVariable("id") Integer id){
        employeeDao.deleteEmployee(id);
        return "redirect:/emps";
    }


}
